const express = require('express')
const router = express.Router()
const axios = require('axios')

// 获取token
async function get_token() {
  // 请求access-token 的地址
  const options = {
    'method': 'POST',
    'url': 'https://aip.baidubce.com/oauth/2.0/token?client_id=4UwvYxGkoVFWnr71OVbCjsLe&client_secret=YctxTGiQj3e7H24QH7QvLePwrmwkcknd&grant_type=client_credentials',
    'headers': {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }

  const result = await axios(options)
  const token = result.data.access_token
  return token
}

const messages = []

router.get('/api-chat', async (req, res) => {

  const content = req.body.content

  messages.push({
    role: 'user',
    content
  })

  const token = await get_token()

  const result = await axios.post('https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' + token, {
    messages
  })

  messages.push({
    role: 'assistant',
    content: result.data.result
  })

  res.send(messages)

})

module.exports = router